package com.haiyi.software.xmpp.service;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.DefaultPacketExtension;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;

import com.haiyi.software.app.MainApplication;
import com.haiyi.software.app.R;
import com.haiyi.software.dao.ChatDAO;
import com.haiyi.software.entity.EntityChat;
import com.haiyi.software.tools.L;
import com.haiyi.software.tools.MyTools;
import com.haiyi.software.xmpp.event.XMPPStream;

public abstract class HIChatServicesXMPPOperation extends Service implements
		XMPPStream, ConnectionListener {

	private static final String TAG = "HIChatServicesXMPPOperation";
	public static String SERVERIP = "";
	public static int PORT = -1;

	protected MainApplication app;
	protected XMPPConnection connection;
	protected ConnectionConfiguration connConfig;
	private ChatDAO dao;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO 自动生成的方法存根
		return null;
	}

	@Override
	public void onCreate() {
		// TODO 自动生成的方法存根
		super.onCreate();
		// SERVERIP = getResources().getString(R.string.ServerIP);
		SERVERIP = MainApplication.getInstance().getServerIP();
		PORT = Integer.valueOf(getResources().getString(R.string.ServerPort));
		app = MainApplication.getInstance();

	}

	public abstract void xmppLoginSucces(String str);

	public Boolean xmppConnection(String user, String pswd) {

		Boolean isFlag = false;
		new loginOperation(user, pswd).execute(null, null, null);
		return isFlag;
	}

	/**
	 * 把消息存放到数据库中
	 */
	protected void AddReceivedMessageToDB(Message message) {

		EntityChat chat = new EntityChat();

		chat.setBody(message.toXML());
		chat.setDownload("0");

		chat.setRead_state("0");// 对方消息，永远未读

		chat.setHi_id(MyTools.getMessageHiid(message.getFrom()));

		String name = "";

		String uhead = "";

		try {
			name = ((DefaultPacketExtension) message.getExtension(
					"MyExtension", "jabber:client")).getValue("username");

			uhead = ((DefaultPacketExtension) message.getExtension(
					"MyExtension", "jabber:client")).getValue("uhead");
		} catch (Exception e) {
			// TODO: handle exception
			// Log.e("myE", "name，uhead为空:" + e.getMessage());
		}

		chat.setName(name);

		chat.setSiID(message.getPacketID());
		chat.setState("0");
		chat.setUhead(uhead);

		L.i("chat=" + chat.toString());

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		chat.setTimes(df.format(new Date()));

		ChatDAO dao = ChatDAO.getInstence();
		dao.Add(chat);
	}

	private class loginOperation extends AsyncTask<Integer, Integer, String> {
		private String str_user = null;
		private String str_pswd = null;

		private loginOperation(String str_user, String str_pswd) {
			this.str_pswd = str_pswd;
			this.str_user = str_user;
		}

		@Override
		protected String doInBackground(Integer... params) {
			// TODO 自动生成的方法存根
			String str_flag;
			/** 是否启用安全验证 */
			// connConfig.setSASLAuthenticationEnabled(false);

			/** 创建connection链接 */

			try {
				connection.connect();
				connection.login(str_user, str_pswd);

				Presence presence = new Presence(Presence.Type.available);
				connection.sendPacket(presence);
				str_flag = "成功";

			} catch (Exception ex) {

				L.i("ex=" + ex.getMessage());

				connection = null;
				str_flag = ex.getMessage();
			}
			return str_flag;
		}

		@Override
		protected void onPostExecute(String result) {
			if (result == "成功") {
				xmppLoginSucces("成功");
			}
		}
	}
}
